package com.yuqih.common.servlet;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.yuqih.common.json.JacksonObjectMapper;

/**
 * 将RequestContext写到日志文件中
 * 
 * @author yuqih
 *
 */
public class DefaultRequestContextLogger implements IRequestContextLogger {

	protected static final Log logger = LogFactory.getLog("WebRequest");

	@Override
	public void log(RequestContext requestContext) throws Exception {
		
		String requestBody = requestContext.getRequestBody();
		JsonNode requestObject = null;
		if (StringUtils.isNotBlank(requestBody)) {
			try {
				requestObject = JacksonObjectMapper.Default_Object_Mapper.readTree(requestBody);
			} catch (Exception ignore) {
			}
		}
		String content;
		if (requestObject != null) {
			ObjectNode node = JacksonObjectMapper.Default_Object_Mapper.valueToTree(requestContext);
			node.remove("requestBody");
			node.set("requestObject", requestObject);
			content = JacksonObjectMapper.Default_Object_Mapper.writeValueAsString(node);
		} else{
			content = JacksonObjectMapper.Default_Object_Mapper.writeValueAsString(requestContext);
		}
		
		if (requestContext.getResponseStatus() >= 400 || requestContext.getError() != null) {
			logger.error(content);
		} else {
			logger.info(content);
		}
	}

}
